package com.edgclub.edg.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.adapter.BBDetailImageAdapter;
import com.edgclub.edg.adapter.BBMoreReplyAdapter;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.model.Reply;
import com.edgclub.edg.model.Topic;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.TopicMoreReplyData;
import com.edgclub.edg.uc.DeleteDialog;
import com.edgclub.edg.uc.SpaceItemDecoration;
import com.edgclub.edg.uc.TopicDetailDialog;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.DateUtils;
import com.edgclub.edg.utils.util.DensityUtils;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.rockerhieu.emojicon.EmojiconTextView1;
import com.squareup.otto.ThreadEnforcer;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 2016/5/20.
 */
public class GzTopicMoreReplyActivity extends GzBaseTooolBarActivity implements View.OnClickListener,VolleyListener{

    // 回复
    public  static final int REQUEST_CODE_REPLYCOMMENT = 0x1112;
    public  static final int REQUEST_CODE_BACK = 0x1113;

    private XRecyclerView recyclerView;
    private BBMoreReplyAdapter bbAdapter;
    private View headView;
    private LinearLayout topic_bar;

    private Topic topic;
    private Reply reply;
    private  Reply  replycomment;
    private ArrayList<User> likeUsers;
    private boolean fristInActivity = true;
    private int currPage = 1;
    private int pageSize = 20;
    private boolean isLoading = false;
    private User user;
    private UserPrefUtils userPrefUtils;

    private TopicApi topicApi;
    private GlideUtils glideUtils;
    private ArrayList<Reply> detailList;

    /***********头部***************/
    private EmojiconTextView1 topic_content;
    private TextView reply_time,user_name,tv_zan_count;
    private ImageView user_icon,even_more,tv_owner,imgv_zan;
    private RecyclerView unableScrollRecycleView;
    private ScaleAnimation scaleAnimation;

    private int spacingInPixels;

    private int clickposition;//评论的position


    @Override
    public int getContentView() {
        return R.layout.activity_topic_more_reply;
    }

    @Override
    public void setTitleBarView() {
        setCustomActionBar();
//        title.setText("楼层");
        main_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setReplysEventBus();
            }
        });
    }



    @Override
    public void initView() {
        spacingInPixels = DensityUtils.dip2px(this,12);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);

        recyclerView = (XRecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        headView =   LayoutInflater.from(this).inflate(R.layout.head_bb_more_reply, (ViewGroup)findViewById(android.R.id.content),false);
        initHeadView(headView);
        recyclerView.addHeaderView(headView);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                currPage = 1;
                getMoreReply();
            }

            @Override
            public void onLoadMore() {
                getMoreReply();
            }
        });
    }

    @Override
    public void initData() {
        userPrefUtils = new UserPrefUtils(this);
        user = userPrefUtils.getUser();
        topicApi = new TopicApi(this);
        glideUtils = new GlideUtils();
        detailList = new ArrayList<>();
        bbAdapter = new BBMoreReplyAdapter(this);
        bbAdapter.setReplyArrayList(detailList);
        bbAdapter.setReplyOnclickListener(new MyReplyClickListener());
        recyclerView.setAdapter(bbAdapter);
        topic = (Topic) getIntent().getSerializableExtra("topic");
        scaleAnimation = new ScaleAnimation(1.0f,
                2.0f, 1.0f, 2.0f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(400);

        //点赞星星动画
        ScaleAnimation starScaleAnimation = new ScaleAnimation(0.5f, 1.5f, 1.0f, 1.5f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        starScaleAnimation.setDuration(400);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setDuration(400);
        reply = (Reply) getIntent().getSerializableExtra("replyfloor");
        if(getIntent().hasExtra("replycomment")){
            replycomment = (Reply) getIntent().getSerializableExtra("replycomment");
        }
        clickposition = getIntent().getIntExtra("clickposition",-1);

        setHeadContent(reply);
        bbAdapter.setTopic(topic);
        if(reply!=null && reply.getReplys()!=null && reply.getReplys().size()>0){
            detailList.addAll(reply.getReplys());
            if(reply.getReplys().size()>=pageSize){
                currPage++;
            }
        }
        if(getIntent().getBooleanExtra("load",false)) {
            getMoreReply();
        }


        Intent intent = new Intent(GzTopicMoreReplyActivity.this, GzTopicReplyTopicActivity.class);
        intent.putExtra("topicId", topic.getPostsId());
        intent.putExtra("clickposition",clickposition);
        if(replycomment!=null){
            intent.putExtra("clickreply",replycomment);
            intent.putExtra("isReplyComment",true);
        }else{
            intent.putExtra("clickreply", reply);
        }
        startActivityForResult(intent, REQUEST_CODE_REPLYCOMMENT);

    }

    private void getMoreReply() {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topic.getPostsId());
        postsParam.setPage(currPage + "");
        postsParam.setPageSize(pageSize+"");
        postsParam.setUserId(user.getId() + "");
        postsParam.setReplyId(reply.getId()+"");
        topicApi.moreReply(postsParam,this);
    }


    @Override
    public void onStart(String tag) {

        isLoading = true;
//        if (fristInActivity) {
//            showDialog("正在获取...", true);
//            fristInActivity = false;
//        }
    }

    @Override
    public void onSuccess(String response, String tag) {
        isLoading = false;
        int code = JSONHelper.getResultCode(response);
        dismissDialog();
        recyclerView.refreshComplete();
        recyclerView.loadMoreComplete();
        if (JSONHelper.isSuccess(response)) {
            if(tag.equals(ApiConfig.APIURL.URL_POSTS_MOREREPLY)){
                TopicMoreReplyData data = JsonUtil.getMode(response, TopicMoreReplyData.class);
                if(null!=data&&null!=data.getData()) {
                    if(currPage==1){
                        Reply comment = data.getData().getComment();
                        reply=comment;
                        if(null!=comment)
                        setHeadContent(comment);
                    }
                    ArrayList<Reply> replys = data.getData().getReplys();
                    if (replys != null && replys.size() > 0) {
                        if (currPage == 1) {
                            detailList.clear();
                        }
                        detailList.addAll(replys);
                        bbAdapter.setReplyArrayList(detailList);
                        bbAdapter.notifyDataSetChanged();
                        currPage++;
                    } else {
                        recyclerView.noMoreLoading();
                    }
                }
            }
        }else if(code == 6002){

        }else if(code == 9004){

        }else{

        }
    }
    @Override
    public void onFaile(VolleyError volleyError, String tag) {
        dismissDialog();
        isLoading = false;
        recyclerView.refreshComplete();
        recyclerView.loadMoreComplete();
        ResultCode.toastVolleyError(this, volleyError);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.even_more:
                boolean res = false;
                boolean isDeleteReply = false;
                if (userPrefUtils.isDeletReply()){
                    isDeleteReply = true;
                }
                if (reply.getUser().getId().equals(user.getId())
                    || topic.getUser().getId().equals(userPrefUtils.getUser().getId())){
                    res = true;
                }
                final TopicDetailDialog dialog = TopicDetailDialog.create(GzTopicMoreReplyActivity.this,res , isDeleteReply);
                dialog.show();
                dialog.setReplyListener(new TopicDetailDialog.ReplyClickListener() {
                    @Override
                    public void replyClick() {
//                        Reply clickReply = detailList.get(position);
                        Intent intent = new Intent(GzTopicMoreReplyActivity.this,
                                GzTopicReplyTopicActivity.class);
                        intent.putExtra("clickreply", reply);
                        intent.putExtra("topicId", topic.getPostsId());
                        startActivityForResult(intent, REQUEST_CODE_REPLYCOMMENT);
                        dialog.dismiss();
                    }
                });
                dialog.setDeletelListener(new TopicDetailDialog.DeleteClickListener() {
                    @Override
                    public void deleteClick() {
                        deleteDialog("reply", reply);
                        dialog.dismiss();
                    }
                });
                dialog.setReportListener(new TopicDetailDialog.ReportClickListener() {
                    @Override
                    public void reportClick() {
//                        Intent intent = new Intent(GzTopicMoreReplyActivity.this, GzTopicReportActivity.class);
//                        intent.putExtra("topic", topic);
//                        intent.putExtra("reply", reply);
//                        startActivity(intent);
//                        dialog.dismiss();
                    }
                });
                break;
            case R.id.imgv_zan:
                if (reply.isLiked()) {
                    replyunlikePost(reply);
                    imgv_zan.setImageResource(R.drawable.bb_zan_selector);
                    if (reply.getLikes()>0){
                        tv_zan_count.setText((reply.getLikes() - 1)+"");
                        if (tv_zan_count.getText().toString().equals("0")){
                            tv_zan_count.setVisibility(View.GONE);
                        }else{
                            tv_zan_count.setVisibility(View.VISIBLE);
                        }
                    }else{
                        tv_zan_count.setVisibility(View.GONE);
                    }
                    imgv_zan.setSelected(false);
                    reply.setLiked(false);
                    reply.setLikes(reply.getLikes() - 1);
                    bbAdapter.notifyDataSetChanged();
                } else {
                    replylikePost(reply);
                    imgv_zan.setImageResource(R.drawable.good2);
                    imgv_zan.startAnimation(scaleAnimation);
                    scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }
                        @Override
                        public void onAnimationEnd(Animation animation) {
                            imgv_zan.setImageResource(R.drawable.bb_zan_selector);
                            tv_zan_count.setVisibility(View.VISIBLE);
                            tv_zan_count.setText((reply.getLikes() + 1)+"");
                            imgv_zan.setSelected(true);
                            reply.setLiked(true);
                            reply.setLikes(reply.getLikes() + 1);
                            bbAdapter.notifyDataSetChanged();

                        }
                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                }
                break;
        }
    }
    private void replylikePost(Reply reply) {
        PostsParam param = new PostsParam();
        param.setUserId(userPrefUtils.getUser().getId() + "");
        param.setPostsId(topic.getPostsId());
        param.setReplyId(reply.getId() + "");
        topicApi.likereplyPost(param, new ReplyLikePostListener(reply, "like"));
    }

    private void replyunlikePost(Reply reply) {
        PostsParam param = new PostsParam();
        param.setUserId(userPrefUtils.getUser().getId() + "");
        param.setPostsId(topic.getPostsId());
        param.setReplyId(reply.getId() + "");
        topicApi.unlikereplyPost(param, new ReplyLikePostListener(reply, "unlike"));
    }

    /**
     * 点赞的监听
     */
    class ReplyLikePostListener implements VolleyListener {
        private Reply reply;
        private String type;

        public ReplyLikePostListener(Reply reply, String type) {
            this.reply = reply;
            this.type = type;
        }

        @Override
        public void onStart(String tag) {

        }

        @Override
        public void onSuccess(String response, String tag) {
            if (JSONHelper.isSuccess(response)) {
                if (type.equals("like")) {
//                    reply.setLikesCount((Integer.parseInt(reply.getLikesCount())+1)+"");
//                    reply.setLiked(true);
                } else {
//                    reply.setLikesCount((Integer.parseInt(reply.getLikesCount())-1)+"");
//                    reply.setLiked(false);
                }
//                bbAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
// dismissDialog();
            ResultCode
                    .toastVolleyError(GzTopicMoreReplyActivity.this, volleyError);
        }
    }
    private void deleteDialog(final String type, final Reply tmpreply) {
        final DeleteDialog dialog = DeleteDialog.create(this, true);
        dialog.show();
        dialog.setCancelable(true);
        dialog.setTitle(StringUtils.getString(R.string.prompt));
        if (userPrefUtils.isDeletTopic()){
            dialog.setContent("正在使用管理员删除功能，确定删除这个帖子么？");
        } else {
            dialog.setContent("是否删除");
        }
        dialog.setSubmittext("确定");
        dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

            @Override
            public void cancelClick() {
                dialog.dismiss();
            }
        });
        dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                if(type.equals("comment")){
                    deleteReply("comment",tmpreply);
                }else if(type.equals("reply")){
                    deleteReply("reply",tmpreply);
                }
                dialog.dismiss();

            }
        });
    }


    class MyReplyClickListener implements BBMoreReplyAdapter.ReplyCommentOnclickListener {
        @Override
        public void replyComment(int position,Reply reply) {
            Intent intent = new Intent(GzTopicMoreReplyActivity.this,
                    GzTopicReplyTopicActivity.class);
            intent.putExtra("topicId", topic.getPostsId());
            intent.putExtra("clickreply",reply);
            intent.putExtra("isReplyComment",true);
            startActivityForResult(intent, REQUEST_CODE_REPLYCOMMENT);
        }

        @Override
        public void deleteComment(int position, Reply reply) {
            deleteDialog("comment",reply);
        }

    }

    /**
     * 删除回复
     */
    private void deleteReply(String type,Reply reply) {
        if (isLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topic.getPostsId());
        postsParam.setReplyId(reply.getId()+"");
        postsParam.setUserId(user.getId() + "");
        topicApi.deleteReply(postsParam,new DelReplyListener(type,reply));
    }
    class DelReplyListener implements VolleyListener {

        String type;
        Reply deleteReply;

        public DelReplyListener(String type,Reply deleteReply) {
            super();
            this.type = type;
            this.deleteReply = deleteReply;
        }

        @Override
        public void onStart(String tag) {
            showDialog("正在删除...",true);
        }

        @Override
        public void onSuccess(String response,String tag) {
            dismissDialog();
            if (JSONHelper.isSuccess(response)) {
                if(type.equals("reply")){
                    HashMap<String, Object> hashMap = new HashMap<String, Object>();
                    hashMap.put("event", BroadCastEvent.TOPICDELETETOPICORREPLY);
                    hashMap.put("reply", deleteReply);
                    EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                            ThreadEnforcer.MAIN).post(hashMap);
                    finish();
                }else if(type.equals("comment")){
                    detailList.remove(deleteReply);
                    reply.setRemainReplys(reply.getRemainReplys()-1);
                    bbAdapter.notifyDataSetChanged();
                }
            } else {
                Toast.makeText(GzTopicMoreReplyActivity.this, "删除失败",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFaile(VolleyError volleyError,String tag) {
            dismissDialog();
            ResultCode.toastVolleyError(GzTopicMoreReplyActivity.this, volleyError);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == REQUEST_CODE_REPLYCOMMENT){
            showToast("回复成功");
            if(detailList.size()<pageSize){
                Reply reply1 = (Reply) data.getSerializableExtra("reply");
                detailList.add(detailList.size(),reply1);
            }
            reply.setRemainReplys(reply.getRemainReplys()+1);
            bbAdapter.setReplyArrayList(detailList);
            bbAdapter.notifyDataSetChanged();
        }else if(resultCode == REQUEST_CODE_BACK){
            setReplysEventBus();
        }
    }


    private void initHeadView(View view){
        topic_content = (EmojiconTextView1) view.findViewById(R.id.topic_content);
        reply_time = (TextView) view.findViewById(R.id.reply_time);
        user_name = (TextView) view.findViewById(R.id.user_name);
        tv_zan_count = (TextView) view.findViewById(R.id.tv_zan_count);
        tv_owner = (ImageView) view.findViewById(R.id.tv_owner);
        user_icon = (ImageView) view.findViewById(R.id.user_icon);
        even_more = (ImageView) view.findViewById(R.id.even_more);
        imgv_zan = (ImageView) view.findViewById(R.id.imgv_zan);
        even_more.setOnClickListener(this);
        imgv_zan.setOnClickListener(this);
        unableScrollRecycleView = (RecyclerView) view.findViewById(R.id.unableScrollRecycleView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        unableScrollRecycleView.setLayoutManager(layoutManager);
        unableScrollRecycleView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));
    }
    private void setHeadContent(Reply reply){
        if(reply==null)return;
        if(reply.getUser()!=null){
            user_name.setText(reply.getUser().getNick()+"");
            glideUtils.Glidde_loadCropCircleImage(this,reply.getUser().getLogo(),user_icon);
            if(topic.getUser()!=null && topic.getUser().getId().equals(reply.getUser().getId())){
                tv_owner.setVisibility(View.VISIBLE);
            }else{
                tv_owner.setVisibility(View.GONE);
            }
        }
        String num = reply.getFloor()==null?"1":reply.getFloor();
        title.setText(num+"楼");
        if(getIntent().getBooleanExtra("yuantie",false)) {
            right_layout.setVisibility(View.VISIBLE);
            right_text.setVisibility(View.VISIBLE);
            right_text.setText("查看原帖");
            right_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(GzTopicMoreReplyActivity.this,GzTopicDetailActivity.class);
                    intent.putExtra("topicId", topic.getPostsId());
                    startActivity(intent);
                }
            });
        }else{
            right_layout.setVisibility(View.GONE);
        }
        reply_time.setText(num
                + "楼"+"  "
                + DateUtils
                .getTimestampStringBB(Long.valueOf(reply.getUpdateAt())));
        /*****************内容*****************/
        topic_content.setVisibility(View.VISIBLE);
        if(TextUtils.isEmpty(reply.getContent())){
            topic_content.setVisibility(View.GONE);
        }
        topic_content.setText(reply.getContent());

        //是否点赞
        if(reply.getLikes()>0){
            tv_zan_count.setVisibility(View.VISIBLE);
            tv_zan_count.setText(reply.getLikes()+"");
        }else{
            tv_zan_count.setVisibility(View.GONE);
        }
        if(reply.isLiked()){
            imgv_zan.setSelected(true);
        }else{
            imgv_zan.setSelected(false);
        }


        /*****************图片*****************/
        unableScrollRecycleView.setVisibility(View.VISIBLE);
        ArrayList<PostsAlbum> albums = reply.getAlbums();
        if (albums != null && albums.size() > 0) {
            BBDetailImageAdapter imageAdapter = new BBDetailImageAdapter(this);
            unableScrollRecycleView.setAdapter(imageAdapter);
            int ww = (int) this.getResources().getDimension(R.dimen.size_90);
            int tmpW = DensityUtils.getScreenW(this) - ww;
            int totalHeight = 0;
            for(int i = 0;i<albums.size();i++){
                PostsAlbum album = albums.get(i);
                int width = album.getWidth();
                int height = album.getHeight();
                if(width==0 || height == 0){
                    album.setWidth(tmpW);
                    album.setHeight(tmpW);
                }else{
                    if(width>tmpW){
                        album.setWidth(tmpW);
                    }else{
                        album.setWidth(width);
                    }
                    album.setHeight(album.getWidth()*height/width);
                }
                totalHeight = totalHeight+album.getHeight();
            }
            ViewGroup.LayoutParams params =  unableScrollRecycleView.getLayoutParams();
            params.width = tmpW;
            params.height = totalHeight+(albums.size()-1)*spacingInPixels;
            unableScrollRecycleView.setLayoutParams(params);
            imageAdapter.setPostsAlbums(albums);
            imageAdapter.notifyDataSetChanged();

        } else {
           unableScrollRecycleView.setVisibility(View.GONE);
        }

    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setReplysEventBus();
    }

    private void setReplysEventBus(){
        try {
            HashMap<String, Object> hashMap = new HashMap<String, Object>();
            hashMap.put("event", BroadCastEvent.TOPICREPLYLIST);
            hashMap.put("replys", detailList);
            hashMap.put("clickposition",clickposition);
            hashMap.put("remainReplys",reply.getRemainReplys());
            hashMap.put("likes",reply.getLikes());
            hashMap.put("liked",reply.isLiked());
            EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                    ThreadEnforcer.MAIN).post(hashMap);
        } catch (Exception e){
            e.printStackTrace();
        }
        finish();
    }


}
